using System.IO;
using Jurassic;
using Kiwi.Node.Modules;

namespace Kiwi.Node
{
    public class Module : IModule
    {
        public Module(IApplication application, ScriptSource scriptSource)
        {
            Application = application;
            Engine = application.CreateScriptEngine();

            ModuleRootFolder = string.IsNullOrEmpty(scriptSource.Path)
                                   ? Application.RootFolder
                                   : Path.GetDirectoryName(scriptSource.Path);

            Initialize(scriptSource);
        }

        protected string ModuleRootFolder { get; private set; }

        public IApplication Application { get; set; }

        #region IModule Members

        public ScriptEngine Engine { get; private set; }

        public object Exports { get; set; }

        #endregion

        private void Initialize(ScriptSource scriptSource)
        {
            var global = Engine.Global;
            global["__filename"] = scriptSource.Path ?? "";
            global["__dirname"] = Engine.String.Construct(ModuleRootFolder);

            Engine.Execute(new EmbeddedScriptSource("Kiwi.Node.Lib.amd.js.internal"));

            global["process"] = Application.ProcessObject;
            global["jsruntime"] = Engine.CallGlobalFunction("require", "jsruntime");
            global["console"] = Engine.CallGlobalFunction("require", "console");

            Engine.Evaluate(scriptSource);

            Exports = global["exports"];
        }
    }
}